/*
 * @Description: 计算数据
 * @Author: HuiSir<github.com/huisir001>
 * @Date: 2022-08-09 10:58:04
 * @LastEditTime: 2025-08-16 18:36:35
 */
import { defineStore } from "pinia";
import { computed, ComputedRef } from "vue";
import LocalCache from "@/utils/LocalCache";
import { project } from "@/init/config";
import useAdminStore from "./modules/admin";
import useLayoutStore from "./modules/layout";
import { deepCopy, rawList2Tree } from "@/ui";
import { AdminTypeOpt } from "@/helpers/selection";

export default defineStore("getters", () => {
  const adminStore = useAdminStore();

  /**
   * 取Token
   * Token存store和localStorage两处,防止用户在登录状态清理浏览器缓存
   * 查询时若一处被清理则回填
   * getter在返回一个函数时，函数的返回值不会被缓存
   */
  const getToken = computed(() => {
    const { token: S_TOKEN, setStates } = adminStore;
    const C_TOKEN = LocalCache.getCache(project.storage.token);
    if (C_TOKEN) {
      setStates({ token: C_TOKEN });
      return C_TOKEN;
    } else if (S_TOKEN) {
      LocalCache.setCache(project.storage.token, S_TOKEN);
      return S_TOKEN;
    } else {
      return null;
    }
  });
  /**
   * 拷贝管理员信息
   */
  const copyAdminInfo: ComputedRef<AdminInfo> = computed(() =>
    deepCopy(adminStore.adminInfo || {})
  );
  /**
   * 是否超管
   */
  const superAdmin = computed(
    () => adminStore.adminInfo?.type === AdminTypeOpt.super
  );
  /**
   * menu转tree
   */
  const menuTree = computed(() =>
    rawList2Tree({
      rawList: adminStore.menus,
      ancestorId: project.defaultTreeData.ancestorId,
    })
  );
  /**
   * 拷贝historyRoutes
   */
  const copyHistRoutes = computed(() =>
    deepCopy(useLayoutStore().historyRoutes)
  );

  return {
    getToken,
    copyAdminInfo,
    superAdmin,
    menuTree,
    copyHistRoutes,
  };
});
